#!/usr/bin/python3
# -*- coding: utf-8 -*-
import glob
import os
import os.path
import re
import sys
import time
import j264_utils

def timestampToSeconds( timestamp ):
    """
    @summary: Converts a timestamp from ProjectX log into seconds.

    @param timestamp: The input timestamp.
    """
    ( prefix, fractions ) = timestamp.split( '.' )
    ( hours, minutes, seconds ) = prefix.split( ':' )
    return int( hours ) * 3600.0 + int( minutes ) * 60.0 + int( seconds ) + int( fractions ) / 1000.0

def bytesToString( inputLine ):
    """
    @summary: Convert a byte array into a string.

    @param retVal: Line to convert.
    """
    retVal = ''
    try:
        retVal = inputLine.decode( 'utf-8' ).strip()
    except:
        try:
            retVal = inputLine.decode( 'cp1252' ).strip()
        except:
            try:
                retVal = inputLine.decode( 'ascii' ).strip()
            except:
                retVal = None
    return retVal

def processLogDirectory( fileList ):
    """
    @summary: Searches for ProjectX's log file from the specified directory,
    and processes it for guessing the correct aspect ratio for the
    video.

    @param inputDir: A directory to use for searching for a log file.
    """
    for logDir in fileList.keys():
        for logFile in fileList[logDir]:
            logFilename = os.path.abspath( logDir ) + os.path.sep + logFile
            print( "#", logFilename )
            videoLength = 0
            videoBasics = re.compile( "video basics:", re.I )
            newFormat = re.compile( "new format in next", re.I )
            summary = re.compile( "summary of created media files", re.I )
            videoLength = re.compile( "Frames\s*([\.:\d]*)\s*'" )
            insideParenthesis = re.compile( "\((.*)\)", re.I )
            previousLine = ''
            previousTime = 0
            aspectRatioTimes = {}
            cumulativeTimes = {}
            ar = ''
            timeInSeconds = 0
            # Process the file.
            for _line in open( logFilename, "rb" ):
                # Convert read bytes into a string.
                line = bytesToString( _line )
                # Is this a 'video basics' line?
                if videoBasics.search( line ) is not None:
                    # Store the aspect ratio.
                    try:
                        ar = insideParenthesis.search( line ).group( 1 )
                    except:
                        pass
                    continue
                # Is this a 'new format' line?
                if newFormat.search( line ) is not None:
                    try:
                        timeInSeconds = timestampToSeconds( insideParenthesis.search( line ).group( 1 ) )
                    except:
                        pass
                    aspectRatioTimes[timeInSeconds] = ar
                    continue
                # Check for summary.
                if summary.search( previousLine ) is not None:
                    # Frames[whitespace]00:48:50.080[whitespace]'
                    mo = videoLength.search( line )
                    if mo is not None:
                        videoLength = timestampToSeconds( mo.group( 1 ) )
                        aspectRatioTimes[videoLength] = ar
                # Store previous line.
                previousLine = line
            for key in sorted( aspectRatioTimes.keys() ):
                try:
                    cumulativeTimes[aspectRatioTimes[key]] += key - previousTime
                except:
                    cumulativeTimes[aspectRatioTimes[key]] = key - previousTime
                previousTime = key
            pct = 0
            ar = ''
            for key in cumulativeTimes.keys():
                cumulativeTime = cumulativeTimes[key]
                cumulativeTimes[key] = 100.0 * cumulativeTimes[key] / videoLength
                print( "#", "%4s" % key, "%4d" % cumulativeTime, "%5.1f%%" % cumulativeTimes[key] )
                if cumulativeTimes[key] > pct:
                    pct = cumulativeTimes[key]
                    ar = key
            if pct > 60:
                print( 'SCALE=\"$SCALE_%s\"' % ar.replace( ':', '_' ) )
            else:
                print( 'SCALE=\"$SCALE_x\"' )

#~ 'Main'
if __name__ == "__main__":
    args = sys.argv[1:]
    #~ Sanity checking.
    if not len( args ):
        print( ">>>No input directories specified", file = sys.stderr )
        sys.exit( 2 )

    # Process input directories.
    for inputDir in args:
        dirPart = inputDir
        if os.path.isfile( inputDir ):
            dirPart, filePart = os.path.split( inputDir )
        j264_utils.processInputDir( dirPart, 'log\.txt', processLogDirectory )
